package com.bajiao.service.store.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bajiao.common.exception.DataHandleException;
import com.bajiao.dto.store.*;
import com.bajiao.entity.classify.Classify;
import com.bajiao.entity.order.OrderDetails;
import com.bajiao.entity.reserve.Reserve;
import com.bajiao.entity.store.Store;
import com.bajiao.mapper.store.StoreMapper;
import com.bajiao.service.classify.ClassifyService;
import com.bajiao.service.order.OrderDetailsService;
import com.bajiao.service.reserve.ReserveService;
import com.bajiao.service.store.StoreService;
import com.bajiao.service.visitor.VisitorService;
import com.bajiao.vo.store.*;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 店铺表
 * @Author: FanJq
 * @Date:   2024-12-12
 * @Version: V1.0
 */
@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    @Resource
    private VisitorService visitorService;
    @Resource
    private ReserveService reserveService;
    @Resource
    private ClassifyService classifyService;
    @Resource
    private OrderDetailsService orderDetailsService;

    /**
     * @Description
     * 获取行业列表
     * @date 2024/12/12 17:33
     * @author FanJq
     * @param request
     * @return {@link List< StoreResponse>}
    */
    @Override
    public List<StoreResponse> getStoreList(StoreRequest request) {
        List<StoreResponse> storeList = super.baseMapper.getStoreList(request);
        storeList.forEach(store -> store.setDistance(store.getDistance() + "km"));
        return storeList;
    }

    /**
     * @Description
     * 获取店铺详情
     * @date 2024/12/13 10:07
     * @author FanJq
     * @param request
     * @return {@link StoreDetailsResponse}
    */
    @Override
    public StoreDetailsResponse getStoreDetails(String userId, StoreDetailsRequest request) {
        StoreDetailsResponse storeDetails = super.baseMapper.getStoreDetails(request);
        if (storeDetails.getStatus() == 0)
            throw new DataHandleException("商家已闭店");
        storeDetails.setDistance(storeDetails.getDistance() + "km");
        storeDetails.setSliderImageList(Arrays.asList(storeDetails.getSliderImage().split(StringPool.COMMA)));
        List<Classify> classifyList = classifyService.getByStoreId(request.getStoreId());
        storeDetails.setClassifyList(classifyList);
        if (StrUtil.isNotBlank(userId)) {
            Reserve reserve = reserveService.getToday(userId, request.getStoreId());
            if (ObjectUtil.isNotNull(reserve))
                storeDetails.setIsReserve(Boolean.TRUE);
        }
        //@create by FanJq 2024/12/13 10:23 处理浏览记录
        this.addBrowse(request.getStoreId());
        return storeDetails;
    }

    /**
     * @Description
     * 获取商家名称
     * @date 2024/12/23 10:29
     * @author FanJq
     * @param storeId
     * @return {@link String}
    */
    @Override
    public String getStoreTitle(String storeId) {
        Store store = super.lambdaQuery().select(Store::getTitle).eq(Store::getId, storeId).one();
        return ObjectUtil.isNotNull(store) ? store.getTitle() : "";
    }

    /**
     * @Description
     * 修改店铺信息
     * @date 2024/12/26 15:55
     * @author FanJq
     * @param storeId
     * @param request
     * @return
    */
    @Override
    public void modifyStoreInfo(String storeId, StoreEditRequest request) {
        Store store = super.getById(storeId);
        Boolean modify = Boolean.FALSE;
        LambdaUpdateChainWrapper<Store> updateSql = super.lambdaUpdate().eq(Store::getId, storeId);
        if (StrUtil.isNotBlank(request.getCover()) && !StrUtil.equals(store.getCover(), request.getCover())) {
            updateSql.set(Store::getCover, request.getCover());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getOpenHours()) && !StrUtil.equals(store.getOpenHours(), request.getOpenHours())) {
            updateSql.set(Store::getOpenHours, request.getOpenHours());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getLongitude()) && !StrUtil.equals(store.getLongitude(), request.getLongitude())) {
            updateSql.set(Store::getLongitude, request.getLongitude());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getLatitude()) && !StrUtil.equals(store.getLatitude(), request.getLatitude())) {
            updateSql.set(Store::getLatitude, request.getLatitude());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getSliderImage()) && !StrUtil.equals(store.getSliderImage(), request.getSliderImage())) {
            updateSql.set(Store::getSliderImage, request.getSliderImage());
            modify = Boolean.TRUE;
        }
        if (ObjectUtil.isNotNull(request.getStatus()) && request.getStatus() > 0 && store.getStatus() != request.getStatus()) {
            updateSql.set(Store::getStatus, request.getStatus());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getAddress()) && !StrUtil.equals(store.getAddress(), request.getAddress())) {
            updateSql.set(Store::getAddress, request.getAddress());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getProvince()) && !StrUtil.equals(store.getProvince(), request.getProvince())) {
            updateSql.set(Store::getProvince, request.getProvince());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getProvinceCode()) && !StrUtil.equals(store.getProvinceCode(), request.getProvinceCode())) {
            updateSql.set(Store::getProvinceCode, request.getProvinceCode());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getCity()) && !StrUtil.equals(store.getCity(), request.getCity())) {
            updateSql.set(Store::getCity, request.getCity());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getCityCode()) && !StrUtil.equals(store.getCityCode(), request.getCityCode())) {
            updateSql.set(Store::getCityCode, request.getCityCode());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getDistrict()) && !StrUtil.equals(store.getDistrict(), request.getDistrict())) {
            updateSql.set(Store::getDistrict, request.getDistrict());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getDistrictCode()) && !StrUtil.equals(store.getDistrictCode(), request.getDistrictCode())) {
            updateSql.set(Store::getDistrictCode, request.getDistrictCode());
            modify = Boolean.TRUE;
        }
        if (StrUtil.isNotBlank(request.getMobile()) && !StrUtil.equals(store.getMobile(), request.getMobile())) {
            updateSql.set(Store::getMobile, request.getMobile());
            modify = Boolean.TRUE;
        }
        if (modify) {
            updateSql.update();
        }
    }

    /**
     * @Description
     * 店铺财务数据
     * @date 2024/12/27 15:13
     * @author FanJq
     * @param storeId
     * @return {@link StoreStatResponse}
    */
    @Override
    public StoreStatResponse getStoreFinancial(String storeId) {
        //@create by FanJq 2024/12/27 15:13 今日核销面额
        BigDecimal todayAmount = super.baseMapper.getTodayAmount(storeId);
        //@create by FanJq 2024/12/27 15:14 今日核销券数量
        Long todayNum = super.baseMapper.getTodayNum(storeId);
        //@create by FanJq 2024/12/27 15:14 昨日核销面额
        BigDecimal yesterdayAmount = super.baseMapper.getYesterdayAmount(storeId);
        //@create by FanJq 2024/12/27 15:15 昨日核销券数量
        Long yesterdayNum = super.baseMapper.getYesterdayNum(storeId);
        //@create by FanJq 2024/12/27 15:19 近七天营业额
        List<StoreRecentDays> recentDaysList = super.baseMapper.getRecentDaysList(storeId);
        //@create by FanJq 2024/12/27 15:20 本月核销面额
        BigDecimal thisMonthAmount = super.baseMapper.getThisMonthAmount(storeId);
        //@create by FanJq 2024/12/27 15:20 本月核销券数量
        Long thisMonthNum = super.baseMapper.getThisMonthNum(storeId);
        //@create by FanJq 2024/12/27 15:21 上月核销面额
        BigDecimal lastMonthAmount = super.baseMapper.getLastMonthAmount(storeId);
        //@create by FanJq 2024/12/27 15:21 上月核销券数量
        Long lastMonthNum = super.baseMapper.getLastMonthNum(storeId);
        //@create by FanJq 2024/12/27 15:22 组装返回数据
        return new StoreStatResponse(todayAmount, todayNum, yesterdayAmount, yesterdayNum, recentDaysList, thisMonthAmount, thisMonthNum, lastMonthAmount, lastMonthNum);
    }

    /**
     * @Description
     * 获取店铺总营业额
     * @date 2024/12/27 17:49
     * @author FanJq
     * @param storeId
     * @return {@link Map< String, String>}
    */
    @Override
    public Map<String, String> getStoreTotalFinancial(String storeId) {
        //@create by FanJq 2024/12/27 17:50 总核销面额
        BigDecimal totalAmount = super.baseMapper.getTotalAmount(storeId);
        //@create by FanJq 2024/12/27 17:50 总核销券数量
        Long totalNum = super.baseMapper.getTotalNum(storeId);
        return new HashMap<String, String>(){{
            put("totalAmount", totalAmount.stripTrailingZeros().toPlainString());
            put("totalNum", totalNum.toString());
        }};
    }

    /**
     * @Description
     * 门店商品订单
     * @date 2024/12/28 10:45
     * @author FanJq
     * @param storeId
     * @return {@link List< StoreOrderResponse>}
    */
    @Override
    public List<StoreOrderResponse> getStoreOrderPage(String storeId) {
        List<StoreOrderResponse> storeOrderList = super.baseMapper.getStoreOrderPage(storeId);
        storeOrderList.forEach(storeOrder -> {
            List<OrderDetails> detailsList = orderDetailsService.getByOrderNo(storeOrder.getOrderNo());
            storeOrder.setOrderDetails(detailsList);
        });
        return storeOrderList;
    }

    /**
     * @Description
     * 门店优惠券订单
     * @date 2024/12/28 10:48
     * @author FanJq
     * @param storeId
     * @return {@link List< StoreCouponOrderResponse>}
    */
    @Override
    public List<StoreCouponOrderResponse> getStoreCouponOrderPage(String storeId) {
        return super.baseMapper.getStoreCouponOrderPage(storeId);
    }

    /**
     * @Description
     * 管理后台列表
     * @date 2025/1/3 16:45
     * @author FanJq
     * @param account
     * @param title
     * @param mobile
     * @return {@link List< StoreAdmin>}
    */
    @Override
    public List<StoreAdmin> getAdminList(String account, String title, String mobile) {
        List<StoreAdmin> resultList = super.baseMapper.getAdminList(account, title, mobile);
        return resultList;
    }

    /**
     * @Description
     * 店铺统计列表
     * @date 2025/1/9 17:52
     * @author FanJq
     * @param title
     * @return {@link List< StoreStatistics>}
    */
    @Override
    public List<StoreStatistics> getStatisticsList(String title) {
        return super.baseMapper.getStatisticsList(title);
    }

    /**
     * @Description
     * 店铺核销记录
     * @date 2025/1/9 18:07
     * @author FanJq
     * @param keywords
     * @param orderNo
     * @param storeTitle
     * @param title
     * @param createTimeBegin
     * @param createTimeEnd
     * @return {@link List< StoreVerify>}
    */
    @Override
    public List<StoreVerify> getVerifyList(String keywords, String orderNo, String storeTitle, String title, String createTimeBegin, String createTimeEnd) {
        return super.baseMapper.getVerifyList(keywords, orderNo, storeTitle, title, createTimeBegin, createTimeEnd);
    }

    /**
     * @Description
     * 处理浏览记录
     * @date 2024/12/13 10:23
     * @author FanJq
     * @param storeId
     * @return
    */
    private void addBrowse(String storeId) {
        //@create by FanJq 2024/12/13 10:21 递增浏览量
        super.lambdaUpdate().setSql("browse = browse + 1").eq(Store::getId, storeId).update();
        visitorService.record();
    }
}
